package com.itestor.iptv.global.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;


/**
 * 
 * @author Mr.li
 *
 */
public class ITestFileUtil {

    /**
     * 
     */
    private static final Logger logger =Logger.getLogger(ITestFileUtil.class);
    
    /**
     * Download. Remote-File
     * @param remoteURL
     * @param localURL
     * @throws FileNotFoundException 
     * @throws MalformedURLException 
     * @throws IOException 
     */
    public static void copyFile(String remoteURL, String localURL) throws FileNotFoundException ,MalformedURLException,IOException{
        URL url=null;
        InputStream inputStream=null;
        OutputStream outputStream=null;
        
        try {
            url=new URL(remoteURL);            
            inputStream=url.openStream();   
            File localFile=new File(localURL);            
            FileUtils.forceMkdir(localFile.getParentFile());           
            outputStream =new FileOutputStream(localURL);            
            IOUtils.copy(inputStream, outputStream);            
        } catch (MalformedURLException e) {
            logger.error(e.getMessage());
            throw e;
        } catch (FileNotFoundException e ){ 
            logger.error(e.getMessage());
            throw e;
        }catch (IOException e) {
            logger.error(e.getMessage());
            throw e;
        }finally{
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }      
        
    }
    
    /**
     * @param filePath
     * @return boolean
     */
    public static boolean isExistsFile(String filePath){
        File localFile=new File(filePath);       
        return  localFile.exists();
    }
    
    /**
     * 
     * @param args
     */
    public static void main(String[] args) {
        try {
            ITestFileUtil.copyFile("http://127.0.0.1/itest\2010-09-25\18-26-40.015-ES.mp4" ,"D:\\download\\videoss\\2010-09-27\\1.mp4");
        } catch (FileNotFoundException e) {            
            e.printStackTrace();
        } catch (MalformedURLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }       
    }
    
    
        
}
